import React, { Component } from 'react'
import { ActivityIndicator, FlatList, Image, Text, View } from 'react-native'

export default class App extends Component {
  // refreshing:代表刷新动画的状态
  state={result:[],refreshing:false}
  componentDidMount(){
    const url='https://api.apiopen.top/getWangYiNews?page=1';
    fetch(url)
    .then(res=>res.json())
    .then(res=>{
      console.log(res);
      this.setState({result:res.result})
    })
  }

  page=1;//初始值
  _onEndReached=()=>{
    // alert('侦测到触底');
    // 获取下一页的数据
    const nextPage=this.page+1;//加载更多是下一页
    const url='https://api.apiopen.top/getWangYiNews?page='+nextPage;


    fetch(url)
    .then(res=>res.json())
    .then(res=>{
      console.log(res);
      //新旧数据合并
      this.setState({result:this.state.result.concat(res.result)});
      //更新当前页数
      this.page=nextPage;
    })
  }

  _onRefresh=()=>{
    // alert('下拉刷新');
    this.setState({refreshing:true})
    //重新获取第一页数据
    const url='https://api.apiopen.top/getWangYiNews?page=1';

    fetch(url)
    .then(res=>res.json())
    .then(res=>{
      console.log(res);
      //刷新动画停止：false,请求的结果替换旧的
      this.setState({refreshing:false,result:res.result});
      this.page=1;//重置当前页数为第一页
    })

  }

  render() {
    /**
     * 触底事件：onEndReached
     * 触底阈值：onEndReachedThreshold，0.1代表10%，剩余未出现的内容高度/列表高度
     */
    return (
      <FlatList 
              refreshing={this.state.refreshing}
              onRefresh={this._onRefresh}
              onEndReachedThreshold={0.1}
              onEndReached={this._onEndReached}
              data={this.state.result}
              keyExtractor={(item,index)=>index+''}
              renderItem={this._renderItem}
              ItemSeparatorComponent={()=>(
                <View style={{height:1,backgroundColor:'gray'}}/>
              )}
              ListFooterComponent={this._ListFooterComponent}
      />
    )
}
_ListFooterComponent=()=>(
  <View style={{alignItems:'center',padding:7,backgroundColor:'white'}}>
    <ActivityIndicator color="red" size="large"/>
    <Text style={{fontSize:25,color:'gray'}}>加载中...</Text>
  </View>
)
_renderItem=({item})=>(
  <View style={{padding:5,flexDirection:'row'}}>
    <Image source={{uri:item.image}} style={{width:150,height:100}}/>
    <View style={{marginLeft:5,flex:1,justifyContent:'space-around'}}>
      <Text style={{fontSize:23}} numberOfLines={2}>{item.title}</Text>
      <Text style={{fontSize:19,color:'gray'}}>{item.passtime}</Text>
    </View>
  </View>
)
}
